import { useState, useEffect, useRef } from "react";
import data from "@emoji-mart/data";
import Picker from "@emoji-mart/react";

interface EmojiProps {
  onSelect: (emoji: string) => void; // 可以根据实际的 emoji 类型替换 `any`
}

export function Emoji({ onSelect }: EmojiProps) {
  const [isShow, setIsShow] = useState(false);

  // 使用 useRef 引用弹框容器和按钮
  const emojiButtonRef = useRef<HTMLButtonElement>(null);
  const emojiPickerRef = useRef<HTMLDivElement>(null);

  // 点击外部区域时关闭弹框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      // 如果点击的位置不在按钮和弹框内，关闭弹框
      if (
        emojiButtonRef.current &&
        !emojiButtonRef.current.contains(event.target as Node) &&
        emojiPickerRef.current &&
        !emojiPickerRef.current.contains(event.target as Node)
      ) {
        setIsShow(false);
      }
    };

    // 监听文档的点击事件
    document.addEventListener("mousedown", handleClickOutside);

    // 清除事件监听
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <div className="relative">
      <button
        ref={emojiButtonRef}
        className="w-12 h-12 bg-[#424656] border-[#505567] hover:bg-[#2E313D] active:bg-[#505567] transition-all duration-100  border-[1px] rounded-full flex justify-center items-center"
        onClick={() => setIsShow(!isShow)}
      >
        <img
          src="src/assets/img/emoji/smiling-face.png"
          className="w-9 h-9 object-fit"
        />
      </button>
      {isShow && (
        <div
          ref={emojiPickerRef}
          className="absolute z-10 -top-[450px] left-[50%] -translate-x-[50%]"
        >
          <Picker
            data={data}
            locale="zh"
            theme="dark"
            onEmojiSelect={(emoji: Record<string, string>) =>
              onSelect(emoji.native)
            }
          />
        </div>
      )}
    </div>
  );
}
